package com.sdp.wx.controller;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sdp.core.bizc.db.Query;
import com.sdp.core.bizc.vo.DataCenter;
import com.sdp.core.bizc.vo.Result;
import com.sdp.flow.db.entity.ActHiComment;
import com.sdp.flow.db.service.IWorkflowService;
import com.sdp.flow.dto.FlowParam;
import com.sdp.flow.utils.FlowConstants;
import com.sdp.wx.db.wx_assets_scrap_report.entity.WxAssetsScrapReport;
import com.sdp.wx.db.wx_assets_scrap_report.service.IWxAssetsScrapReportService;
import com.sdp.wx.db.wx_assets_scrap_report_detail.entity.WxAssetsScrapReportDetail;
import com.sdp.wx.db.wx_assets_scrap_report_detail.service.IWxAssetsScrapReportDetailService;
import com.sdp.wx.utils.CurrentLoginEmp;
import com.sdp.wx.utils.SequenceNoUtils;
import com.sdp.wx.utils.WxConstants;
import com.sdp.wx.view.WxAssetsScrapReportDetailView;


/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author zsp
 * @since 2024-03-01
 */
@RestController
@RequestMapping("/WxAssetsScrapReportController")
public class WxAssetsScrapReportController {
	
	@Autowired
	private Query query;
	
	@Autowired
	private IWxAssetsScrapReportService assetsScrapReportService;
	
	@Autowired
	private IWxAssetsScrapReportDetailService assetsScrapReportDetailService;
	
	@Autowired
	private CurrentLoginEmp currentLoginEmp;
	
	@Autowired
	private IWorkflowService workflowService;
	
	public static final String 报废报告模版_包含电子产品 = "process_d8imal4i";
	
	public static final String 报废报告模版_不包含电子产品 = "process_28s76997";
	
	
	@PostMapping(value = "/page")
	public Result<?> page(@RequestBody DataCenter dataCenter) {
		return Result.ok(query.page(assetsScrapReportService, WxAssetsScrapReport.class, dataCenter));
	}
	
	/*
	 * 报废明细试图分页查询
	 */
	@PostMapping(value = "/viewPage")
	public Result<?> viewPage(@RequestBody DataCenter dataCenter) {
		QueryWrapper<WxAssetsScrapReportDetailView> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("b.report_status", WxConstants.流程审批状态_审批通过.getCode())
			.eq("a.scrap_status", WxConstants.否.getCode());
		return Result.ok(query.viewPage(assetsScrapReportDetailService, WxAssetsScrapReportDetailView.class, dataCenter, queryWrapper));
	}
	
	@PostMapping(value = "/getReportAssetsList")
	public Result<?> getReportAssetsList(@RequestBody DataCenter dataCenter) {
		return Result.ok(query.list(assetsScrapReportDetailService, WxAssetsScrapReportDetail.class, dataCenter));
	}
	
	@PostMapping(value = "/save")
	@Transactional(rollbackFor=Exception.class)
	public Result<?> save(@RequestBody JSONObject obj) {
	
		if(obj==null || obj.get("formData")==null){
			return Result.error("报告信息为空");
		}
		
		List<WxAssetsScrapReportDetail> assetsList = JSONArray.parseArray(JSON.toJSONString(obj.get("assetsList")), WxAssetsScrapReportDetail.class);
		WxAssetsScrapReport assetsScrapReport = JSONObject.parseObject(JSON.toJSONString(obj.get("formData")), WxAssetsScrapReport.class);
		
		JSONObject emp = currentLoginEmp.getCurrentLoginInfo();
		if (emp == null || !emp.containsKey("empNo")) {
			return Result.error("当前登录人信息为空");
		}
		
		if(StringUtils.isEmpty(assetsScrapReport.getKeyId())) {
			assetsScrapReport.setReportCode(SequenceNoUtils.getSequenceNo(SequenceNoUtils.报废报告申请单));
			assetsScrapReport.setReportStatus(WxConstants.流程审批状态_未提交.getCode());
			assetsScrapReport.setEmpNo(emp.getString("empNo"));
			assetsScrapReport.setEmpName(emp.getString("empName"));
			assetsScrapReport.setCreateTime(LocalDateTime.now());
			assetsScrapReportService.save(assetsScrapReport);
			
		}else {
			assetsScrapReportService.updateById(assetsScrapReport);
		}
		
		//先删除后新增
		QueryWrapper<WxAssetsScrapReportDetail> queryWrapper = new QueryWrapper<>();
		queryWrapper.lambda().eq(WxAssetsScrapReportDetail::getReportId, assetsScrapReport.getKeyId());
		assetsScrapReportDetailService.remove(queryWrapper);
		
		for (WxAssetsScrapReportDetail wxAssetsScrapReportDetail : assetsList) {
			if (wxAssetsScrapReportDetail.getCreateTime() == null) {
				wxAssetsScrapReportDetail.setCreateTime(LocalDateTime.now());
			}
			wxAssetsScrapReportDetail.setKeyId(null);
			wxAssetsScrapReportDetail.setScrapStatus(WxConstants.否.getCode());
			wxAssetsScrapReportDetail.setReportId(assetsScrapReport.getKeyId());
		}
		assetsScrapReportDetailService.saveBatch(assetsList);
		
		return Result.ok(assetsScrapReport);
	}
	
	@PostMapping(value = "/saveAndStartFlow")
	@Transactional(rollbackFor=Exception.class)
	public Result<?> saveAndStartFlow(@RequestBody JSONObject obj) {
		if(obj==null || obj.get("formData")==null || obj.get("assetsList")==null){
			return Result.error("报告信息为空");
		}
	
		List<WxAssetsScrapReportDetail> assetsList = JSONArray.parseArray(JSON.toJSONString(obj.get("assetsList")), WxAssetsScrapReportDetail.class);
		WxAssetsScrapReport assetsScrapReport = JSONObject.parseObject(JSON.toJSONString(obj.get("formData")), WxAssetsScrapReport.class);
		
		JSONObject emp = currentLoginEmp.getCurrentLoginInfo();
		if (emp == null || !emp.containsKey("empNo")) {
			return Result.error("当前登录人信息为空");
		}
		
		if(StringUtils.isEmpty(assetsScrapReport.getKeyId())) {
			assetsScrapReport.setReportCode(SequenceNoUtils.getSequenceNo(SequenceNoUtils.报废报告申请单));
			assetsScrapReport.setReportStatus(WxConstants.流程审批状态_未提交.getCode());
			assetsScrapReport.setEmpNo(emp.getString("empNo"));
			assetsScrapReport.setEmpName(emp.getString("empName"));
			assetsScrapReport.setCreateTime(LocalDateTime.now());
			assetsScrapReportService.save(assetsScrapReport);
			
		}else {
			assetsScrapReportService.updateById(assetsScrapReport);
		}
		
		//先删除后新增
		QueryWrapper<WxAssetsScrapReportDetail> queryWrapper = new QueryWrapper<>();
		queryWrapper.lambda().eq(WxAssetsScrapReportDetail::getReportId, assetsScrapReport.getKeyId());
		assetsScrapReportDetailService.remove(queryWrapper);
		
		for (WxAssetsScrapReportDetail wxAssetsScrapReportDetail : assetsList) {
			if (wxAssetsScrapReportDetail.getCreateTime() == null) {
				wxAssetsScrapReportDetail.setCreateTime(LocalDateTime.now());
			}
			wxAssetsScrapReportDetail.setKeyId(null);
			wxAssetsScrapReportDetail.setScrapStatus(WxConstants.否.getCode());
			wxAssetsScrapReportDetail.setReportId(assetsScrapReport.getKeyId());
		}
		assetsScrapReportDetailService.saveBatch(assetsList);
		
		if (WxConstants.是.getCode().equals(assetsScrapReport.getContainStatus())) {
			assetsScrapReport.setTemplateId(报废报告模版_包含电子产品);
		} else {
			assetsScrapReport.setTemplateId(报废报告模版_不包含电子产品);
		}
		//设置审批状态
		assetsScrapReport.setReportStatus(WxConstants.流程审批状态_审批中.getCode());
		
		//发起流程
		FlowParam flowParam = new FlowParam();
		flowParam.setUserId(emp.getString("empNo"));
		flowParam.setTemplateId(assetsScrapReport.getTemplateId());
		flowParam.setBizId(assetsScrapReport.getKeyId());
		//指定审批人
		Map<String, Object> variableMap = new HashMap<>();
		variableMap.put(FlowConstants.FLOW_ASSIGN_PERSON_KEY, assetsScrapReport.getApprover());
		flowParam.setVariableMap(variableMap);
		//启动工作流
		String instanceId = workflowService.startFlowAndCommit(flowParam);
		if (StringUtils.isEmpty(instanceId)) {
			throw new RuntimeException("流程启动失败!");
		}
		//发起成功设置流程实例Id
		assetsScrapReport.setInstanceId(instanceId);
		assetsScrapReportService.updateById(assetsScrapReport);
				
		return Result.ok(assetsScrapReport);

	}
	
	/**
	 * 流程提交
	 * @param contract
	 * @return
	 */
	@PostMapping(value = "/commit")
	@Transactional(rollbackFor=Exception.class)
	public Result<?> commit(@RequestBody WxAssetsScrapReport report) {
		if(report == null){
			return Result.error("信息为空");
		}
		JSONObject emp = currentLoginEmp.getCurrentLoginInfo();
		if (emp == null || !emp.containsKey("empNo")) {
			return Result.error("当前登录人信息为空");
		}
		//提交流程
		if (StringUtils.isEmpty(report.getTaskId())) {
			return Result.error("流程信息不完整");
		}
		FlowParam flowParam = new FlowParam();
		flowParam.setUserId(emp.getString("empNo"));
		
		flowParam.setTaskId(report.getTaskId());

		//流程提交参数
		Map<String, Object> variableMap = new HashMap<>();
		variableMap.put("isPass", report.getIsPass());
		variableMap.put("link", report.getLink());
		variableMap.put("userName", emp.getString("empName"));
		variableMap.put("userAvatar", emp.getString("profilePicture"));
		variableMap.put("userSign", emp.getString("nameSign"));
		//设置流程表单对象
		variableMap.put("flowData", report);
		if (!StringUtils.isEmpty(report.getIsPass())) {

			if (WxConstants.否.getCode().equals(report.getIsPass())) {
				variableMap.put(FlowConstants.FLOW_ASSIGN_PERSON_KEY, report.getEmpNo());
				if(StringUtils.isEmpty(report.getApprovalOpinion())){
					report.setApprovalOpinion("不同意");
				}
				report.setReportStatus(WxConstants.流程审批状态_驳回.getCode());
			}else {
				if(StringUtils.isEmpty(report.getApprovalOpinion())){
					report.setApprovalOpinion("同意");
				}
				variableMap.put(FlowConstants.FLOW_ASSIGN_PERSON_KEY, report.getApprover());
				report.setReportStatus(WxConstants.流程审批状态_审批中.getCode());
			}
			
			flowParam.setVariableMap(variableMap);
			
			//更新审批人列表
			report.setApproversList((report.getApproversList()==null?"":report.getApproversList())+("["+emp.getString("empNo")+"]"));

		}
		
		if (!StringUtils.isEmpty(report.getApprovalOpinion())) {
			flowParam.setOpinion(report.getApprovalOpinion());
		}
		
		assetsScrapReportService.updateById(report);
		workflowService.commitTask(flowParam);
		
		return Result.ok(report);
	}
	
	/**
	 * 流程撤销
	 * @param instanceId
	 * @return
	 */
	@GetMapping(value = "/cancel")
	@Transactional(rollbackFor=Exception.class)
	public Result<?> cancel(@RequestParam(name="instanceId",required=true) String instanceId) {
		LambdaQueryWrapper<WxAssetsScrapReport> query = new LambdaQueryWrapper<>();
		query.eq(WxAssetsScrapReport::getInstanceId, instanceId);
		WxAssetsScrapReport report = assetsScrapReportService.getOne(query);
		if(report==null) {
			return Result.error("信息不存在，不能进行撤销");
		}
		JSONObject emp = currentLoginEmp.getCurrentLoginInfo();
		if(!report.getEmpNo().equals(emp.getString("empNo"))) {
			return Result.error("不是填写人，不能进行撤销操作");
		}
		
		//流程撤销
		workflowService.stopFlow(instanceId, "撤销");
		
		assetsScrapReportService.removeById(report.getKeyId());
		QueryWrapper<WxAssetsScrapReportDetail> queryWrapper = new QueryWrapper<>();
		queryWrapper.lambda().eq(WxAssetsScrapReportDetail::getReportId, report.getKeyId());
		assetsScrapReportDetailService.remove(queryWrapper);
		
		return Result.ok(report.getKeyId());
	}
	
	@RequestMapping(value="/queryByInstanceId")
	public Result<?> queryByInstanceId(@RequestParam String instanceId) {
		if (StringUtils.isEmpty(instanceId)) {
			return Result.error("instanceId不能为空!");
		}
		QueryWrapper<WxAssetsScrapReport> queryWrapper = new QueryWrapper<>();
		queryWrapper.lambda().eq(WxAssetsScrapReport::getInstanceId, instanceId);
		WxAssetsScrapReport report = assetsScrapReportService.getOne(queryWrapper, false);
		List<ActHiComment> commentList = workflowService.getApprovedOpinionNew(instanceId);
		report.setApprovalOpinions(commentList);
		return Result.ok(report);
	}
	
}

